package com.cngphone.AnFetion.Fetion.SIPC;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.cngphone.AnFetion.FetionFriend;
import com.cngphone.AnFetion.FetionMessage;
import com.cngphone.AnFetion.FetionSIPC;
import com.cngphone.AnFetion.FetionService;
import com.cngphone.AnFetion.MiscUtil;
import com.cngphone.AnFetion.SendSMSActivity;
import com.cngphone.AnFetion.Settings;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive.IPackageReceivedHandler;
import com.cngphone.AnFetion.tools.LogUtil;
import com.cngphone.AnFetion.tools.StrUtil;
import com.cngphone.AnFetion2.R;

public class IMReceiver extends SIPCBase implements IPackageReceivedHandler {
    private static final String TAG = "IMReceiver";

    public static int FETION_NOTIFYCATION_ID = Settings.FRIEND_NOTIFYCATION_ID + 1;

    private FetionService context;
    private ArrayList<FetionFriend> buddies = null;

    private ArrayList<FetionFriend> getBuddies() {
        if (buddies == null) {
            buddies = context.getFriendManager().getBuddies();
        }
        return buddies;
    }

    public IMReceiver(SerialManager serialManager, TcpSendAndReceive connection, Context context) {
        super(serialManager, connection);
        this.context = (FetionService) context;
    }

    @Override
    public boolean received(FetionSIPC sipc) {
        try {
            if (sipc.isResponse()) return false;
            String cmd = sipc.getRequestCmdLine().cmd;
            if (cmd.equals("M")) {// 收到短消息
                // message.from
                String from = sipc.GetHeaderValue("F");

                FetionFriend fetionFriend = context.getFriendManager().getFriend(from);

                if (fetionFriend == null) {
                    context.setLastError("Receive message whose sender is not in buddies' list:" + from);
                    return false;
                }

                // ((FetionService)context).setLastError(sipc.body); //Tiger. Debug

                // 去掉字体信息
                Pattern pattern = Pattern.compile("<Font(.*?)>(.*?)</Font>");
                Matcher matcher = pattern.matcher(sipc.body);
                if (matcher.find()) sipc.body = matcher.group(2);
                sipc.body = StrUtil.xmlToString(sipc.body);

                from = fetionFriend.getName();
                String msg = from + " : " + sipc.body;
                fetionFriend.addMessage(new FetionMessage(fetionFriend, sipc.body, null));
                fetionFriend.lastMessage = sipc.body;

                // bangbang.song@gmail.com
                // delegate to Service to do it.
                // FIXME: a temple solution.
                context.saveMessage(StrUtil.getPeopleId(fetionFriend.Uri), StrUtil.getPeopleId(context
                        .getMyself().Uri), sipc.body);

                SendSMSActivity chatActivity = FetionService.chatActivity;

                if (chatActivity != null && chatActivity.getFetionFriend() == fetionFriend) {
                    chatActivity.onReceiveMessage();
                } else {
                    if (Settings.DEBUG) LogUtil.d(TAG, msg);
                    int id = fetionFriend.notifyID;
                    if (id <= 0) {
                        id = FETION_NOTIFYCATION_ID++;
                    }
                    // ((FetionService)context).setlastReceivedMessage(sipc.body); //Tiger.
                    // 保存消息，用于在send框显示
                    Notification info = new Notification(R.drawable.fetion, msg, System.currentTimeMillis());
                    info.ledARGB = 0xff00ff00;
                    info.ledOnMS = 1000;
                    info.ledOffMS = 3000;
                    info.flags |= Notification.FLAG_SHOW_LIGHTS;
                    // info.flags = Notification.FLAG_SHOW_LIGHTS;
                    // info.ledOnMS = 1000;
                    // info.ledOffMS = 2000;
                    // info.defaults = Notification.DEFAULT_LIGHTS;
                    // .DEFAULT_SOUND;
                    // R.raw.newmessage
                    // context.getResources().
                    info.sound = Uri.parse("android.resource://com.cngphone.AnFetion/" + R.raw.newmessage);
                    Intent contentIntent = new Intent(context, SendSMSActivity.class);
                    contentIntent.putExtra("uri", fetionFriend.Uri);
                    contentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    // .setData(Uri.parse(sipc
                    // .GetHeaderValue("F")/* + "^" + String.valueOf(id) */));
                    PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent,
                            PendingIntent.FLAG_ONE_SHOT);
                    info.setLatestEventInfo(context, msg, null, appIntent);
                    MiscUtil.getNotificationManager(context).notify(id, info);

                    // message.fetionFriend.setOnStatusBar(true);
                    fetionFriend.notifyID = id;
                    // ((FetionService) context).getFriendsSentNewMessage().add(fetionFriend);
                    // MediaPlayer.create(context.getApplicationContext(),
                    // R.raw.newmessage).start();

                    MiscUtil.notifyReceival(context);
                }

                ArrayList<FetionSIPC.HeaderPair> headers = new ArrayList<FetionSIPC.HeaderPair>();

                headers.add(new FetionSIPC.HeaderPair("F", sipc.GetHeaderValue("F")));
                headers.add(new FetionSIPC.HeaderPair("I", sipc.GetHeaderValue("I")));
                headers.add(new FetionSIPC.HeaderPair("Q", sipc.GetHeaderValue("Q")));
                headers.add(new FetionSIPC.HeaderPair("L", String.valueOf(0)));
                FetionSIPC res = new FetionSIPC("SIP-C/2.0 200 OK", headers, "");
                connection.SendSIPC(res);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean execute() {
        return false;
    }
}
